package gamagora.box2d
{
	import Box2D.Dynamics.Controllers.b2BuoyancyController;
	import Box2D.Dynamics.Controllers.b2Controller;
	import Box2D.Dynamics.b2Body;
	
	import org.flixel.FlxG;
	import org.flixel.FlxGroup;
	import org.flixel.FlxSprite;

	public class OSPhysicWaterBridge extends OSPhysicSprite
	{
		private var _controller:b2BuoyancyController;
		private var _boxes:Vector.<OSPhysicBox>;
		private var _nbBoxes:uint;
		private var _addSprites:Boolean;
		private var _drawWater:Boolean;
		private var _waterSprite:FlxSprite;
		
		public function OSPhysicWaterBridge(x:Number, y:Number, nbBoxes:uint = 10, space:Number = 5, boxWidth:Number = 20, boxHeight:Number = 5, drawWater:Boolean = false)
		{
			super(x, y);
			_nbBoxes = nbBoxes;
			_nbSprites = _nbBoxes;
			_drawWater = drawWater;
				
			_controller = new b2BuoyancyController();
			_controller.normal.Set(0, -1);
			_controller.offset = -y / OSPhysicWorld.ratio;
			_controller.density = 2;
			_controller.linearDrag = 5;
			_controller.angularDrag = 2;
			
			_boxes = new Vector.<OSPhysicBox>();
			
			for(var i:uint=0;i<_nbBoxes;i++)
			{
				var box:OSPhysicBox = new OSPhysicBox(x + i * (boxWidth + space), y, boxWidth, boxHeight);
				box.makeGraphic(boxWidth, boxHeight, 0xff00cc00, true, "water_bridge_box");
				box.setData(OSPhysicData.NOTHING);
				box.getPhysic().bodyDef.type = b2Body.b2_dynamicBody;
				box.getPhysic().fixDef.density = 1;
				box.getPhysic().fixDef.friction = 0.3;
				box.getPhysic().fixDef.restitution = 0.1;
				box.getPhysic().bodyDef.angle = Math.random() * Math.PI;
				_boxes.push(box);
			}
			
			if(_drawWater)
			{
				_waterSprite = new FlxSprite(x, y);
				_waterSprite.makeGraphic(_nbBoxes * (boxWidth + space), 60, 0xaa0000cc);
			}
		}
		
		public override function create(group:FlxGroup):void
		{
			super.create(group);
			
			for(var i:uint=0;i<_nbBoxes;i++)
			{
				_boxes[i].create(group);
				_controller.AddBody(_boxes[i].getBody());
			}
			
			OSPhysicWorld.getInstance().AddController(_controller);
		}
		
		public override function update():void
		{
			for(var i:uint=0;i<_nbBoxes;i++)
			{
				_boxes[i].update();
			}
		}
		
		public override function draw():void
		{
			for(var i:uint=0;i<_nbBoxes;i++)
			{
				_boxes[i].draw();
			}
			
			if(_drawWater)
			{
				_waterSprite.draw();
			}
		}
		
		public override function destroyPhysic():void
		{
			super.destroyPhysic();
			for(var i:uint=0;i<_nbBoxes;i++)
			{
				_controller.RemoveBody(_boxes[i].getBody());
				_boxes[i].destroyPhysic();
			}
			OSPhysicWorld.getInstance().RemoveController(_controller);
		}
		
		//Override
		
		public override function destroy():void
		{
			super.destroy();
			for(var i:uint=0;i<_nbBoxes;i++)
			{
				_boxes[i].destroy();
			}
			
			if(_drawWater)
			{
				_waterSprite.destroy();
			}
		}
	}
}